import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_bluetooth_plugin/flutter_bluetooth_plugin.dart';
import 'package:flutter_bluetooth_plugin_example/BleBean.dart';

import 'HexUtils.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  FlutterBluetoothPlugin _flutterBluetoothPlugin = FlutterBluetoothPlugin();

  @override
  void initState() {
    super.initState();
    FlutterBluetoothPlugin.startListener();
    FlutterBluetoothPlugin.setBlueBlueResultCallback((deviceMessage) {
      var decode = json.decode(deviceMessage);
      var bleBean = BleBean.fromJson(decode);
      if(!has(bleBean)){
        mDeviceList.add(bleBean);

      }

      setState(() {

      });

    });


    FlutterBluetoothPlugin.setBlueMessageCallback((byteData) {
    //var decode = utf8.decode(byteData);

    print(byteData);

      // TODO: implement onReceivedDataListener
      // print("BlePage*****onReceivedDataListener");
      // print(byteData);
      // List<String> list = byteData.map((e) => e.toString()).toList();
      // List<int> list2 = byteData.map((e) => e as int).toList();
      // String data = "";
      // try{
      //   // ASCALL码转换为字符串
      //   data = String.fromCharCodes(list2);
      // }catch(e){
      //   data = "--";
      // }
      // print("data******"+list.toString());
      // print("add**********"+byteData.toString().length.toString());
      // String byteStr = byteData.toList().toString();
      // print("byteStr*****"+jsonEncode(byteData));
      // String tempStr = (data + "( ") + json.encode(byteStr);
      // print("all********"+tempStr.length.toString());
      // print("all********"+tempStr);
      // // 这个地方不用json.encode编码显示不出来
    });
    FlutterBluetoothPlugin.setBlueStateCallback((state) {
      print("state改变了是"+state.toString());

    });
  }

  has(BleBean bleBean){
    for(var ia in mDeviceList){
      if(ia.address==bleBean.address){
        return true;
      }
    }
    return false;
  }


  List<BleBean> mDeviceList = [];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Container(
          child: Column(
            children: [
              RaisedButton(
                onPressed: () async {
                  var bool = await _flutterBluetoothPlugin.turnOn();
                  print(bool);
                },
                child: Text("打开蓝牙"),
              ),
              RaisedButton(
                onPressed: () async {
                  await _flutterBluetoothPlugin
                      .turnOff()
                      .then((value) => {print(value)});
                },
                child: Text("off蓝牙"),
              ),
              RaisedButton(
                onPressed: () {
                  _flutterBluetoothPlugin.startScan();
                },
                child: Text("扫描"),
              ),
              RaisedButton(
                onPressed: () {
                  _flutterBluetoothPlugin.stopScan();
                },
                child: Text("停止扫描"),
              ),
              RaisedButton(
                onPressed: () {
                  _flutterBluetoothPlugin.sendMsg(("我是张宇安卓啥时候找我啥时间啊快点的"));
                },
                child: Text("发送消息"),
              ),
              Expanded(
                  child: ListView.builder(
                    itemBuilder: (context, index) {
                      return getItem(context, mDeviceList[index]);
                    },
                    shrinkWrap: true,
                    padding: EdgeInsets.all(10),
                    itemCount: mDeviceList.length,
                  ))
            ],
          ),
        ),
      ),
    );
  }

  Widget getItem(BuildContext context, BleBean map) {
    return GestureDetector(
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Text(map.name == null ? "空名称" : map.name),
                Text(map.address == null ? "空地址" : map.address),
              ],
            ),
            Text(map.rssi.toString())
          ],
        ),
      ),
      onTap: () async{

        var str= await _flutterBluetoothPlugin.stopScan();
        var decode = json.decode(str);
        if(decode["code"]==200){
          _flutterBluetoothPlugin.connect(map.address);
        }
      },
    );
  }
}
